package com.kotiln.lgc.guidepagedemo.viewpager;

import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.kotiln.lgc.guidepagedemo.R;

import java.util.ArrayList;
import java.util.List;

public class ViewPagerActivity extends AppCompatActivity {

    /**
     * Viewpage实现引导页
     */
    private ViewPager mViewPager;
    private LinearLayout llIndicator;

    private PagerAdapter mPagerAdapter;
    private List<Fragment> mFragmentList = new ArrayList<Fragment>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager);
        mViewPager = findViewById(R.id.viewpager);
        llIndicator = findViewById(R.id.ll);

        for (int i = 0; i < 4; i++) {
            ContentFragment contentFragment = new ContentFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("index", i);
            contentFragment.setArguments(bundle);
            mFragmentList.add(contentFragment);
        }

        //创建适配器
        mPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragmentList);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                for (int i = 0; i < mFragmentList.size(); i++) {
                    llIndicator.getChildAt(i).setBackgroundResource(i == position ? R.drawable.dot_focus : R.drawable.dot_normal);
                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        initIndicator();
    }

    //初始化 圆点 指示器
    private void initIndicator() {
        //dp值 转换为px
        int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10f, getResources().getDisplayMetrics());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, width);
        lp.rightMargin = 2 * width;

        for (int i = 0; i < mFragmentList.size(); i++) {
            View view = new View(this);
            view.setId(i);
            view.setBackgroundResource(i == 0 ? R.drawable.dot_focus : R.drawable.dot_normal);
            view.setLayoutParams(lp);
            llIndicator.addView(view, i);

        }
    }
}